package com.GlobalPaint.app.ui.HTML;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.Adapter.ImagePickerAdapter_xunwu;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.PersonalBean;
import com.GlobalPaint.app.bean.PhotoViewActivity;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.codeBean;
import com.GlobalPaint.app.listener.UILPauseOnScrollListener;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.SiliCompressor;
import com.GlobalPaint.app.utils.UILImageLoader;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.lzy.okhttputils.OkHttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;


public class PutPictureActivity extends AppCompatActivity implements View.OnClickListener, ImagePickerAdapter_xunwu.OnRecyclerViewItemClickListener{

    @BindView(R.id.iv_goback)
    ImageView ivGoback;
    @BindView(R.id.tv_common_center)
    TextView tvCommonCenter;
    @BindView(R.id.tv_fresh)
    TextView tvFresh;
    @BindView(R.id.ed_miaoshu)
    EditText edMiaoshu;
    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    @BindView(R.id.tv_bt)
    EditText tvBt;
    @BindView(R.id.ed_zz)
    TextView edZz;
    @BindView(R.id.ed_gqsj)
    TextView edGqsj;
    private List<PhotoInfo> mDatas = new ArrayList<>();
    private String file1;
    private codeBean codebean;
    private String id;
    File file;
    private PersonalBean personalBean;


    private RecyclerView recyclerView;
    private ImagePickerAdapter_xunwu adapter;
    private int maxImgCount = 9;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_put_picture_activity);
        ButterKnife.bind(this);
        initview();
        id=getIntent().getStringExtra("id");
        tvFresh.setText("发表");
        tvFresh.setVisibility(View.VISIBLE);
        tvCommonCenter.setText("图集发布");
        getInformation();

    }

    private void initview() {
        //查找recyclerView
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mDatas = new ArrayList<PhotoInfo>();

        adapter = new ImagePickerAdapter_xunwu(this, mDatas, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private void getInformation() {
        String url= Constants.JASON_SERVICE_URL+"user/getUserById?userid="+ DataManager.userEntity.getUserId();
        DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), PersonalBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                personalBean=(PersonalBean)o;
                if (personalBean.getStatus() == 1){
                    if(personalBean.getData() != null ){
                        String nick= personalBean.getData().getFNickName()== null?"":
                                personalBean.getData().getFNickName();
                        String mobile= personalBean.getData().getFMobile()== null?"":
                                personalBean.getData().getFMobile();
                        if(nick!=null){
                            edZz.setText(nick);
                        }else {
                            edZz.setText(DataManager.userEntity.getUserName());
                        }
                    }
                }

            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {
                edZz.setText(DataManager.userEntity.getUserName());
            }
        });
    }
    List listimge=new ArrayList<File>();
    @OnClick({R.id.iv_goback, R.id.tv_fresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_goback:
                finish();
                break;
            case R.id.tv_fresh:
                String bt=tvBt.getText().toString();
                if(bt.isEmpty()){
                    Toast.makeText(this,"标题不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
            /*    if(file==null){
                    Toast.makeText(this,"请选择图片",Toast.LENGTH_LONG).show();
                    return;
                }*/


                String ms=edMiaoshu.getText().toString();
                if(ms.isEmpty()){
                    Toast.makeText(this,"请输入描述内容",Toast.LENGTH_LONG).show();
                    return;
                }
                String zz=edZz.getText().toString();
                List<PhotoInfo> actImags = adapter.getImages();
                mDatas.clear();
                for (int i = 0; i < actImags.size(); i++) {
                    mDatas.add(actImags.get(i));
                    file1= SiliCompressor.with(PutPictureActivity.this).compress(mDatas.get(i).getPhotoPath());
                    listimge.add(new File(file1));
                }
                putTuji(bt,listimge,zz,ms);
                break;
        }
    }

    private void dealImages() {

        OkHttpUtils.post("").addFileParams("file",listimge);
    }
    private void putTuji(String bt, List listimge, String zz, String ms) {

        String url = Constants.JASON_SERVICE_URL + "info/saveInfo?fTitle="
                + bt+"&fCreatorId="+DataManager.userEntity.getUserId()+"&fNodeId="+id
                +"&fOffDate="+"2050-03-10 00:00:00"+"&fMetaDescription="+ms+"&fAuthor="+zz+"&token="+DataManager.userEntity.getCookie();
        DataManager.getInst().postHttpRequesFileSClass(url, DataManager.userEntity.getCookie(), listimge,codeBean.class, new DataManager.Callback() {
            @Override
            public void onSuccess(Object o) {
                codebean=(codeBean) o;
                if (codebean.getStatus()==1){
                    finish();
                    Toast.makeText(PutPictureActivity.this,codebean.getMsg(),Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(PutPictureActivity.this,codebean.getMsg(),Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onFailure(ReturnStatusResultEntity error) {

            }
        });
    }
    //打开相册
    private void selectImg() {
      //  mDatas.clear();
        ThemeConfig theme = new ThemeConfig.Builder()
                .build();
        //配置功能
        final FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(false)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setSelected(mDatas)
                .setMutiSelectMaxSize(9)//图片的数量
//                .setFilter(mList)
                .build();
        CoreConfig coreConfig = new CoreConfig.Builder(PutPictureActivity.this, new UILImageLoader(), theme)
                .setFunctionConfig(functionConfig)
                .setPauseOnScrollListener(new UILPauseOnScrollListener(false, true))
                .build();
        GalleryFinal.init(coreConfig);
        String[] function = new String[]{"打开相册", "拍照"};
        final ActionSheetDialog dialog = new ActionSheetDialog(PutPictureActivity.this, function, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);
                        break;
                    case 1:
                        GalleryFinal.openCamera(REQUEST_CODE_CAMERA, functionConfig, mOnHanlderResultCallback);
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {

                for (PhotoInfo result : resultList) {
                    boolean exists = false;
                    for (PhotoInfo photoInfo : mDatas) {
                        if (TextUtils.equals(photoInfo.getPhotoPath(), result.getPhotoPath())) {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        boolean deal = CommUtility.dealRotateImage(result.getPhotoPath());
                        mDatas.add(result);
                    }
                }
                adapter.setImages(mDatas);


                }
        }
        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            CommUtility.ShowMsgShort(PutPictureActivity.this, errorMsg);
        }
    };

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onItemClick(View view, int position) {
        if (position == -1) {
            //选择图片
            selectImg();
        } else {
            Intent intent = new Intent(PutPictureActivity.this, PhotoViewActivity.class);
            intent.putExtra("photoView", mDatas.get(position).getPhotoPath());
            startActivity(intent);
        }
    }
}
